package com.css.fxfzxczh.modules.synthesizeInfoManage.matManage.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.fxfzxczh.constants.FxfzConstants;
import com.css.fxfzxczh.constants.YNEnum;
import com.css.fxfzxczh.modules.synthesizeInfoManage.earEveManage.entity.EarEveManage;
import com.css.fxfzxczh.modules.synthesizeInfoManage.earEveManage.service.EarEveManageService;
import com.css.fxfzxczh.modules.synthesizeInfoManage.matManage.entity.MatManage;
import com.css.fxfzxczh.modules.synthesizeInfoManage.matManage.queryParams.MatManageQuaParams;
import com.css.fxfzxczh.modules.synthesizeInfoManage.matManage.repository.MatManageRepository;
import com.css.fxfzxczh.modules.synthesizeInfoManage.matManage.service.MatManageService;
import com.css.fxfzxczh.modules.synthesizeInfoManage.matManage.verify.MatManageExcelVerify;
import com.css.fxfzxczh.modules.synthesizeInfoManage.matManage.vo.MatManageImportVo;
import com.css.fxfzxczh.util.CreateGson;
import com.css.fxfzxczh.util.PlatformObjectUtils;
import com.css.fxfzxczh.util.UUIDGenerator;
import com.css.fxfzxczh.web.PlatformSessionContext;
import com.css.fxfzxczh.zcpt.sys.entity.SUser;
import com.css.fxfzxczh.zcpt.sys.service.SUserService;
import com.css.fxfzxczh.zcpt.sys.service.SysRoleService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class MatManageServiceimpl implements MatManageService {
    @Resource
    MatManageRepository matManageRepository;

    @Resource
    SysRoleService sysRoleService;

    @Resource
    EarEveManageService earEveManageService;

    @Resource
    SUserService sUserService;

    @Resource
    MatManageExcelVerify matManageExcelVerify;

    @Override
    public Map<String, Object> getPage(MatManageQuaParams queParams, int curPage, int pageSize) {
        Map<String,Object> page=matManageRepository.getPage(queParams, curPage, pageSize);
        return page;
    }

    @Override
    public void delete(String id) {
        MatManage matManage = matManageRepository.findById(id);
        String userId = PlatformSessionContext.getUserID();
        String role = sysRoleService.getRoleByUserId(userId);
        StringBuilder str = new StringBuilder("");
        List<Map> roleMaps = JSONObject.parseArray(role, Map.class);
        for (Map roleMap : roleMaps) {
            str.append(roleMap.get("roleCode") + ",");
        }
        String roles = str.toString();
        if (roles.contains(FxfzConstants.XCZH_COUNTRY_ROLE)) {
            matManageRepository.delete(id);
        }
        if (roles.contains(FxfzConstants.XCZH_PROVINCE_ROLE)) {
            if (!userId.equals(matManage.getCreateUser())) {
                throw new RuntimeException("删除失败，只能删除自己本省下的数据");
            }
            matManageRepository.delete(id);
        }
    }

    @Override
    public void update(MatManage matManage) {
        String userId = PlatformSessionContext.getUserID();
        String role = sysRoleService.getRoleByUserId(userId);
        StringBuilder str=new StringBuilder("");
        List<Map> roleMaps = JSONObject.parseArray(role, Map.class);
        for(Map roleMap:roleMaps){
            str.append(roleMap.get("roleCode")+",");
        }
        String roles = str.toString();
        matManage.setUpdateTime(new Date());
        matManage.setUpdateUser(userId);
        if (roles.contains(FxfzConstants.XCZH_COUNTRY_ROLE)) {
            matManageRepository.update(matManage);
        }
        if(roles.contains(FxfzConstants.XCZH_PROVINCE_ROLE)){
            if (!userId.equals(matManage.getCreateUser())) {
                throw new RuntimeException("修改失败，只能修改自己本省下的数据");
            }
            matManageRepository.update(matManage);
        }
    }

    @Override
    public void save(MatManage matManage) {
        matManage.setXmmId(UUIDGenerator.getUUID());
        matManage.setDelFlag(YNEnum.N.toString());
        matManageRepository.save(matManage);
        earEveManageService.updateRelationStatus(matManage.getXsemId());
    }

    @Override
    public Map<String, Object> getMaterialInfo(String eventCode) {
        EarEveManage currentEvent = earEveManageService.getCurrentEvent();
        eventCode=currentEvent.getEventCode();
        Map<String,Object> map=new HashMap<>();

        StringBuilder headCode = new StringBuilder(eventCode+"WZ");
        DecimalFormat decimalFormat=new DecimalFormat("000");
        String num="";

        String maxNum=matManageRepository.getMaxNum(headCode.toString());
        if(PlatformObjectUtils.isEmpty(maxNum)){
            int i = 1;
            num=decimalFormat.format(i);
        }else{
            String substring = maxNum.substring(maxNum.length() - 3);
            num = decimalFormat.format(Integer.parseInt(substring) + 1);
        }
        map.put("headCode",headCode.append(num).toString());

        String userId = PlatformSessionContext.getUserID();
        String user = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        map.put("createUserName", sUser.getUserName());
        map.put("createUser", sUser.getUserId());
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        map.put("createTime", dateFormat.format(new Date()));
        //map.put("createUnit", sUser.getDeptEntity().getDeptName());
        map.put("createUnit", sUser.getOrgName());
        return map;
    }

    @Override
    public MatManage findById(String id) {
        return matManageRepository.findById(id);
    }

    @Override
    public void importExcel(MultipartFile file, String xsemId) throws Exception {
        List<MatManage> list = new ArrayList<>();
        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        params.setImportFields(new String[]{"物资名称", "物资类型", "物资数量", "描述信息"});
        params.setNeedVerify(true);
        params.setVerifyHandler(matManageExcelVerify);
        String userId = PlatformSessionContext.getUserID();
        String user = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        String userName = sUser.getUserName();
        String orgName = sUser.getOrgName();
        EarEveManage currentEvent = earEveManageService.findById(xsemId);
        InputStream inputStream = file.getInputStream();
        ExcelImportResult<MatManageImportVo> result = ExcelImportUtil.importExcelMore(inputStream, MatManageImportVo.class, params);
        List<MatManageImportVo> failList = result.getFailList();
        if (PlatformObjectUtils.isNotEmpty(failList)) {
            StringBuilder errorMsg = new StringBuilder("<font size='5px' color='red'>导入失败：</font>");
            for (MatManageImportVo matManageImportVo : failList) {
                errorMsg.append("<font size='4px' ><br>").append("第").append(matManageImportVo.getRowNum() + 1).append("行： ").append(matManageImportVo.getErrorMsg()).append("</font>");
            }
            throw new RuntimeException(errorMsg.toString());
        }
        List<MatManageImportVo> resultData = result.getList();//解析excel
        if (!PlatformObjectUtils.isEmpty(resultData)) {
            for (MatManageImportVo item : resultData) {
                Map<String, Object> materialInfo = getMaterialInfo(currentEvent.getEventCode());
                item.setDelFlag(YNEnum.N.toString());
                item.setXmmId(UUIDGenerator.getUUID());
                item.setXsemId(xsemId);
                item.setCreateUser(userId);
                item.setCreateUserName(userName);
                item.setCreateTime(new Date());
                item.setCreateUnit(orgName);
                item.setMaterialCode((String) materialInfo.get("headCode"));
                MatManage matManage = new MatManage();
                BeanUtils.copyProperties(item, matManage);
                list.add(matManage);
            }
        }
        matManageRepository.batchSave(list);

    }
}
